package com.jxpanda.infrastructure.crypto.key.contract;

import com.jxpanda.infrastructure.crypto.model.SecretKeyGenParameterSpec;
import com.jxpanda.infrastructure.crypto.toolkit.Base64Kit;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.NoSuchAlgorithmException;

public interface SecretKeyProvider extends KeyProvider<SecretKey, SecretKeyGenParameterSpec> {

    /**
     * 生成密钥对(使用默认配置生产，方便使用)
     */
    SecretKey generateKey();

    /**
     * 生成对称密钥
     */
    @Override
    default SecretKey generateKey(SecretKeyGenParameterSpec keyGenParameterSpec) {
        try {
            KeyGenerator keyGenerator = KeyGenerator.getInstance(getAlgorithm());
            keyGenerator.init(keyGenParameterSpec.getKeySize());
            return keyGenerator.generateKey();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 从原始字节数组加载密钥（无需 Base64）
     */
    default SecretKey loadSecretKey(byte[] keyBytes) {
        return new SecretKeySpec(keyBytes, getAlgorithm());
    }

    /**
     * 从 Base64 字符串加载对称密钥
     */
    default SecretKey loadSecretKey(String keyString) {
        return new SecretKeySpec(keyString.getBytes(), getAlgorithm());
    }

    /**
     * 从 Base64 字符串加载对称密钥
     */
    default SecretKey loadSecretKeyFromBase64(String base64Key) {
        return new SecretKeySpec(Base64Kit.decode(base64Key), getAlgorithm());
    }

    /**
     * 从文件加载密钥，假设文件内容为 Base64 字符串
     */
    default SecretKey loadSecretKeyFromFile(String filePath) {
        try {
            byte[] data = Files.readAllBytes(Paths.get(filePath));
            return loadSecretKey(new String(data));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
